package com.hbxx.lotteryapp.interceptor;

import com.hbxx.lotteryapp.commons.ApiIdempotent;
import com.hbxx.lotteryapp.commons.TokenService;
import com.hbxx.lotteryapp.entity.LoginUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * token校验拦截器
 */
public class TokenInterceptor implements HandlerInterceptor {
    private Logger logger = LoggerFactory.getLogger(TokenInterceptor.class);

    @Resource
    private TokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            if (method.isAnnotationPresent(ApiIdempotent.class)) {
                if (!checkToken(request)) {
                    failure(response);
                    return false;
                }
            }
        }
        return true;
    }

    private void failure(HttpServletResponse response) throws Exception {
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write("{\"code\": -1, \"message\": \"token校验失败\"}");
    }

    private boolean checkToken(HttpServletRequest request) {
        logger.info("验证token");
        LoginUser loginUser = tokenService.getLoginUser(request);
        if(loginUser != null){
            tokenService.verifyToken(loginUser);
            return true;
        }
        return false;
    }
}
